<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="60%" >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="收支/分类" prop="amountType">
        <el-cascader-panel v-model="cateOptionsTemp" :options="cateTreeOptions" @change="handleCascaderChange" clearable/>
      </el-form-item>
      <el-form-item label="账单标题" prop="billTitle">
        <el-input v-model="formData.billTitle" placeholder="请输入账单标题" style="width: 480px;"/>
      </el-form-item>
      <el-form-item label="账单金额" prop="billAmount">
        <el-input-number v-model="formData.billAmount" :min="0" :max="9999999999" :precision="2" style="width: 240px;"
                         controls-position="right">
          <template #prefix>
            <span>￥</span>
          </template>
        </el-input-number>
      </el-form-item>
      <el-form-item label="变动账户" prop="accountId">
        <el-select
          v-model="formData.accountId"
          placeholder="请选择变动账户"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="item in accountIdOptions"
            :key="item.accountId"
            :label="item.accountName"
            :value="item.accountId"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="账单标签" prop="tags">
        <el-select
          v-model="tagsOptionsTemp"
          placeholder="请选择账单标签"
          clearable
          multiple
          filterable
          @change="handleTagChange"
          style="width: 480px;"
        >
          <el-option
            v-for="item in tagsOptions"
            :key="item.id"
            :label="item.tag"
            :value="item.tag"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="账单阶段" prop="billStage">
        <el-radio-group v-model="formData.billStage">
          <el-radio
            v-for="dict in getStrDictOptions(DICT_TYPE.BILL_STAGE)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="账单状态" prop="billStatus">
        <el-radio-group v-model="formData.billStatus">
          <el-radio
            v-for="dict in getStrDictOptions(DICT_TYPE.BILL_STATUS)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="账单类型" prop="billType">
        <el-radio-group v-model="formData.billType">
          <el-radio
            v-for="dict in getStrDictOptions(DICT_TYPE.BILL_TYPE)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="转账去向" prop="transAccountId" v-show="formData.billType==='转账账单'">
        <el-select
          v-model="formData.transAccountId"
          placeholder="请输入转账去向"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="item in accountIdOptions"
            :key="item.accountId"
            :label="item.accountName"
            :value="item.accountId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="账单时间" prop="billTime">
        <el-date-picker
          v-model="formData.billTime"
          type="datetime"
          value-format="x"
          placeholder="选择账单时间"
          style="width: 240px;"
        />
      </el-form-item>
      <el-form-item label="账单备注" prop="billRemark">
        <el-input v-model="formData.billRemark" placeholder="请输入账单备注" style="width: 480px;"/>
      </el-form-item>
      <el-form-item label="账单来源" prop="extBillSource">
        <el-input v-model="formData.extBillSource" placeholder="请输入账单来源" style="width: 480px;"/>
      </el-form-item>
      <el-form-item label="拓展信息">
        <el-radio-group v-model="extFlag">
          <el-radio key="无"  label="无" > 无 </el-radio>
          <el-radio key="有"  label="有" > 有 </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="外部说明" prop="extRemark" v-show="extFlag === '有'">
        <el-input v-model="formData.extRemark" placeholder="请输入外部说明" style="width: 480px;"/>
      </el-form-item>
      <el-form-item label="外部付款账户" prop="extFromAccount" v-show="extFlag === '有'">
        <el-input v-model="formData.extFromAccount" placeholder="请输入外部付款账户" style="width: 480px;"/>
      </el-form-item>
      <el-form-item label="外部付款人" prop="extFromOwner" v-show="extFlag === '有'">
        <el-input v-model="formData.extFromOwner" placeholder="请输入外部付款人" style="width: 480px;"/>
      </el-form-item>
      <el-form-item label="外部收款账户" prop="extToAccount" v-show="extFlag === '有'">
        <el-input v-model="formData.extToAccount" placeholder="请输入外部收款账户" style="width: 480px;"/>
      </el-form-item>
      <el-form-item label="外部收款人" prop="extToOwner" v-show="extFlag === '有'">
        <el-input v-model="formData.extToOwner" placeholder="请输入外部收款人" style="width: 480px;"/>
      </el-form-item>
      <el-form-item label="补充信息" prop="extInfo" v-show="extFlag === '有'">
        <el-input v-model="formData.extInfo" placeholder="请输入补充信息" style="width: 480px;"/>
      </el-form-item>
<!--      <el-form-item label="外部参数" prop="extParam">-->
<!--        <el-input v-model="formData.extParam" placeholder="请输入外部参数"/>-->
<!--      </el-form-item>-->
      <el-form-item label="是否资产" prop="hasProperty">
        <el-radio-group v-model="formData.hasProperty">
          <el-radio key="否"  :label="0" > 否 </el-radio>
          <el-radio key="是"  :label="1" > 是 </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="资产名称" prop="propertyName" v-show="formData.hasProperty === 1">
        <el-input v-model="formData.propertyName" placeholder="请输入资产名称" style="width: 240px;"/>
      </el-form-item>
      <el-form-item label="资产价值" prop="propertyValue" v-show="formData.hasProperty === 1">
        <el-input-number v-model="formData.propertyValue" :min="0" :max="9999999999" :precision="2" style="width: 240px;"
                         controls-position="right">
          <template #prefix>
            <span>￥</span>
          </template>
        </el-input-number>
      </el-form-item>

      <el-form-item label="资产类别" prop="propertyCate" v-show="formData.hasProperty === 1">
        <el-select
          v-model="formData.propertyCate"
          placeholder="请输入资产类别"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.PROPERTY_CATE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <!--      <el-form-item label="资产参数" prop="propertyParam">-->
      <!--        <el-input v-model="formData.propertyParam" placeholder="请输入资产参数" />-->
      <!--      </el-form-item>-->
      <el-form-item label="资产状态" prop="propertyStatus" v-show="formData.hasProperty === 1">
        <el-radio-group v-model="formData.propertyStatus">
          <el-radio
            v-for="dict in getStrDictOptions(DICT_TYPE.PROPERTY_STATUS)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="资产盘点时间" prop="propertyCheckTime"  v-show="formData.hasProperty === 1">
        <el-date-picker
          v-model="formData.propertyCheckTime"
          type="date"
          value-format="x"
          placeholder="选择资产盘点时间"
          style="width: 240px;"
        />
      </el-form-item>
      <el-form-item label="资产备注" prop="propertyRemark" v-show="formData.hasProperty === 1">
        <el-input v-model="formData.propertyRemark" placeholder="请输入资产备注" style="width: 480px;"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import {BillApi, BillVO} from '@/api/bill/bill'
import {DICT_TYPE, getStrDictOptions} from "@/utils/dict";
import {AccountApi} from '@/api/bill/account'
import {CateApi} from '@/api/bill/bill_cate'
import {TagApi} from "@/api/bill/tag";

/** 账单信息 表单 */
defineOptions({name: 'BillForm'})

const {t} = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  billTitle: undefined,
  billRemark: undefined,
  billAmount: undefined,
  amountType: undefined,
  accountId: undefined,
  cate1: undefined,
  cate2: undefined,
  cate3: undefined,
  tags: undefined,
  templateId: undefined,
  billType: '支付账单',
  billStage: undefined,
  billStatus: '审核通过',
  transAccountId: undefined,
  billTime: undefined,
  extRemark: undefined,
  extFromAccount: undefined,
  extFromOwner: undefined,
  extToAccount: undefined,
  extToOwner: undefined,
  extInfo: undefined,
  extBillSource: undefined,
  extParam: undefined,
  orderNum: 0,
  hasProperty: 0,
  propertyName: undefined,
  propertyCheckTime: undefined,
  propertyCate: undefined,
  propertyValue: undefined,
  propertyParam: undefined,
  propertyRemark: undefined,
  propertyStatus: undefined
})
const formRules = reactive({
  billTitle: [{required: true, message: '账单标题不能为空', trigger: 'blur'}],
  billAmount: [{required: true, message: '账单金额不能为空', trigger: 'blur'}],
  amountType: [{required: true, message: '收支类型不能为空', trigger: 'change'}],
  accountId: [{required: true, message: '变动账户不能为空', trigger: 'blur'}],
  cate1: [{required: true, message: '一级分类不能为空', trigger: 'blur'}],
  cate2: [{required: true, message: '二级分类不能为空', trigger: 'blur'}],
  billType: [{required: true, message: '账单类型不能为空', trigger: 'change'}],
  billStage: [{required: true, message: '账单阶段不能为空', trigger: 'blur'}],
  billStatus: [{required: true, message: '账单状态不能为空', trigger: 'blur'}],
  billTime: [{required: true, message: '账单时间不能为空', trigger: 'blur'}],
  hasProperty: [{required: true, message: '是否为资产不能为空', trigger: 'blur'}]
})
const formRef = ref() // 表单 Ref
const accountIdOptions = ref()
const cateTreeOptions = ref([])
const tagsOptions = ref([])
const extFlag = ref('无')
const tagsOptionsTemp = ref([])
const cateOptionsTemp = ref([])
const getAccountOptions = async () => {
  const data = await AccountApi.getAccountPage({
    pageNo: 1,
    pageSize: 100,
    hasEnable: 1
  })
  accountIdOptions.value = data.list
}
const getTagsOptions = async () => {
  const data = await TagApi.getTagPage({
    pageNo: 1,
    pageSize: 100
  })
  tagsOptions.value = data.list
}
const getCateTreeOptions = async () => {
  const data = await CateApi.getCateTree({})
  cateTreeOptions.value = data
}

const handleCascaderChange = (value) => {
  formData.value.amountType = value[0]
  formData.value.cate1 = value[1]
  formData.value.cate2 = value[2]
  // console.log(queryParams)
}
const handleTagChange = (value) => {
  formData.value.tags = value.join('@')
  // console.log(value)
}
/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = type === 'copy' ? '复用' : t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await BillApi.getBill(id)

      tagsOptionsTemp.value = formData.value.tags.split('@');
      cateOptionsTemp.value = [formData.value.amountType,formData.value.cate1,formData.value.cate2]
      extFlag.value = formData.value.extInfo!== null
      || formData.value.extRemark!==null
      || formData.value.extParam!==null
      || formData.value.extFromAccount!==null
      || formData.value.extFromOwner!==null
      || formData.value.extToAccount!==null
      || formData.value.extToOwner!==null
        ? '有' : '无';
    } finally {
      formLoading.value = false
    }
  }
  if (type === 'copy'){
    formData.value.id = null
  }
}
defineExpose({open}) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as BillVO
    if (formType.value === 'create' || formType.value === 'copy') {
      await BillApi.createBill(data)
      message.success(t('common.createSuccess'))
    } else {
      await BillApi.updateBill(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    billTitle: undefined,
    billRemark: undefined,
    billAmount: undefined,
    amountType: undefined,
    accountId: undefined,
    cate1: undefined,
    cate2: undefined,
    cate3: undefined,
    tags: undefined,
    templateId: undefined,
    billType: '支付账单',
    billStage: undefined,
    billStatus: '审核通过',
    transAccountId: undefined,
    billTime: undefined,
    extRemark: undefined,
    extFromAccount: undefined,
    extFromOwner: undefined,
    extToAccount: undefined,
    extToOwner: undefined,
    extInfo: undefined,
    extBillSource: undefined,
    extParam: undefined,
    orderNum: 0,
    hasProperty: 0,
    propertyName: undefined,
    propertyCheckTime: undefined,
    propertyCate: undefined,
    propertyValue: undefined,
    propertyParam: undefined,
    propertyRemark: undefined,
    propertyStatus: undefined
  }
  tagsOptionsTemp.value = []
  cateOptionsTemp.value = []
  formRef.value?.resetFields()
}

/** 初始化 **/
onMounted(() => {
  getAccountOptions()
  getCateTreeOptions()
  getTagsOptions()
})
</script>
